#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
视频下载工具模块

该模块提供视频下载功能，支持从网络URL下载视频文件到本地。
"""

import os
import logging
import urllib.parse
import requests

# 配置日志
logger = logging.getLogger(__name__)


def is_url(path: str) -> bool:
    """
    判断路径是否为URL
    
    Args:
        path: 文件路径或URL
        
    Returns:
        bool: 如果是URL返回True，否则返回False
    """
    return path.startswith(('http://', 'https://'))


def download_video(url: str, download_dir: str) -> str:
    """
    下载视频到指定目录
    
    Args:
        url: 视频URL
        download_dir: 下载目录路径
        
    Returns:
        str: 下载后的本地文件路径
        
    Raises:
        Exception: 下载失败时抛出异常
    """
    # 确保下载目录存在
    if not os.path.exists(download_dir):
        os.makedirs(download_dir)
    
    # 从URL解析文件名
    parsed_url = urllib.parse.urlparse(url)
    filename = os.path.basename(parsed_url.path)
    if not filename or '.' not in filename:
        filename = f"video_{hash(url) % 10000}.mp4"
    
    local_path = os.path.join(download_dir, filename)
    logger.info(f"开始下载视频: {url} -> {local_path}")
    
    try:
        # 下载文件
        response = requests.get(url, timeout=30)
        response.raise_for_status()
        
        with open(local_path, 'wb') as f:
            f.write(response.content)
        
        logger.info(f"视频下载完成: {local_path}")
        return local_path
    except Exception as e:
        logger.error(f"下载视频失败: {url} - {e}")
        raise Exception(f"下载视频失败: {url} - {e}")


def cleanup_downloaded_file(downloaded_file: str) -> bool:
    """
    清理下载的文件
    
    Args:
        downloaded_file: 下载文件的路径
        
    Returns:
        bool: 清理成功返回True，失败返回False
    """
    if downloaded_file and os.path.exists(downloaded_file):
        try:
            os.remove(downloaded_file)
            logger.info(f"已清理下载的文件: {downloaded_file}")
            return True
        except Exception as e:
            logger.warning(f"清理下载文件失败 {downloaded_file}: {e}")
            return False
    return False


def cleanup_downloaded_files(downloaded_files: list) -> dict:
    """
    清理下载的文件列表
    
    Args:
        downloaded_files: 下载文件路径列表
        
    Returns:
        dict: 包含成功和失败文件信息的字典
    """
    result = {
        "success": [],
        "failed": []
    }
    
    if downloaded_files:
        for file_path in downloaded_files:
            if cleanup_downloaded_file(file_path):
                result["success"].append(file_path)
            else:
                result["failed"].append(file_path)
    
    return result


__all__ = ['is_url', 'download_video', 'cleanup_downloaded_file', 'cleanup_downloaded_files']